import React, { Component } from 'react';
import '../styles/Register.css'
import {user_register} from '../api/index'
class Register extends Component {
    constructor(props){
        super(props);
        this.state = {phone:'',pass:'',agree:false }
    }
    handleChange(e){
        this.setState({
            [e.target.name] : e.target.type == 'checkbox' ? e.target.checked : e.target.value
        })
    }
    register(){
        if (this.state.phone.trim()!='' && this.state.pass.trim()!='') {
            if (/^1[3456789]\d{9}$/.test(this.state.phone)) {
                if (/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])\S*$/.test(this.state.pass)) {
                    user_register({phone:this.state.phone,pass:this.state.pass}).then((res)=>{
                        console.log(res);
                        alert('注册成功')
                        localStorage.setItem('phone',this.state.phone)
                        localStorage.setItem('pass',this.state.pass)
                    })
                }else{
                    alert('密码格式有误')
                } 
            }else{
                alert("手机号格式有误,请核实")
            }
        } else {
            alert('请输入内容')
        }
    }
    render() {
        return (
            <div className='register'>
                <div className="title">注册页</div>
                <div className="block">
                    {/* 对于input textarea select通过value属性和onChange事件让原本非受控的表单元素变为受控元素 */}
                    <input name='phone' value={this.state.phone} onChange={(e)=>{this.handleChange(e)}} type="text" placeholder='输入手机号' />
                </div>
                <div className="block">
                    <input name='pass'  value={this.state.pass} onChange={(e)=>{this.handleChange(e)}} type="text" placeholder='输入密码' />
                </div>
                <div className="block ">
                    <input type="button" value='注册'  onClick={()=>{this.register()}}/>
                    <span onClick={()=>{this.props.history.push('/login')}}>去登录</span>
                </div>
            </div>
        );
    }
}

export default Register;